
'use strict'
const path = require('path')
const defaultSettings = require('./src/settings.js')

// gzip
const CompressionWebpackPlugin = require('compression-webpack-plugin');
const TerserPlugin = require("terser-webpack-plugin");
const productionGzip = true // 是否使用gzip
const productionGzipExtensions = ['js', 'css'] // 需要gzip压缩的文件后缀
// 去掉注释
// const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
// 环境判断
const isProduction = process.env.NODE_ENV === 'production';

function resolve(dir) {
  return path.join(__dirname, dir)
}

// 端口号，可以在.env中设置
// const port = process.env.port || process.env.npm_config_port || 9528 // dev port

// 配置详情：https://cli.vuejs.org/zh/config/
module.exports = {
  publicPath: '/', // 部署应用包时的基本 URL
  outputDir: 'dist',
  assetsDir: 'static',
  lintOnSave: false, // 保存代码时eslint校验，process.env.NODE_ENV === 'development',
  productionSourceMap: false,
  devServer: {
    port: process.env.port,
    open: true,
    hotOnly: true,
    disableHostCheck: true,
    headers: {
      'Access-Control-Allow-Origin': '*'
    },
    watchOptions: {
      ignored: /(node_modules)/
    },
    overlay: {
      warnings: false,
      errors: true
    },
    // before: require('./mock/user.js'),
    proxy: defaultSettings.proxy
  },
  configureWebpack: (config) => {
    config.name = defaultSettings.title
    if(isProduction){
      // 构建时开启gzip,降低服务器压缩对CPU资源的占用，服务器也要相应开启gzip
      productionGzip && config.plugins.push(
        new CompressionWebpackPlugin({
          test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
          threshold: 8192,
          minRatio: 0.8
        })
      )
      config.plugins.push(
        new TerserPlugin({
          cache: true,//降版本后添加
          sourceMap: false,//降版本后添加
          // 多进程
          parallel: true,//降版本后添加
          terserOptions: {
            ecma: undefined,
            warnings: false,
            parse: {},
            compress: {
              drop_console: true,
              drop_debugger: false,
              pure_funcs: ['console.log'], // 移除console
            },
          },
        })
      )
      // config.plugins.push(
      //   new UglifyJsPlugin({
      //     uglifyOptions: {
      //       output: {
      //         comments: false,
      //       },
      //       compress: {
      //         warnings: false,
      //         drop_console: true,
      //         drop_debugger: false,
      //         pure_funcs: ['console.log'] // 移除console
      //       }
      //     }
      //   })
      // )
    }
    config.output.library = 'vue-micro-app'
    config.output.libraryTarget = 'umd'
    config.output.jsonpFunction = 'webpackJsonp_vue-micro-app'
  },
  chainWebpack: (config) => {
    // 它可以提高第一屏的速度，建议开启预加载preload
    config.plugin('preload').tap(() => [
      {
        rel: 'preload',
        // 忽略 runtime.js
        fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
        include: 'initial'
      }
    ])

    // 当页面太多时，会导致太多无意义的请求
    config.plugins.delete('prefetch')

    // 文件输出
    config.output.filename('[name].[hash].js').end()

    // 配置别名
    config.resolve.alias
      .set('@', path.resolve('src'))
      .set('assets', path.resolve('src/assets'))
      .set('components', path.resolve('src/components'))

    // 配置svg
    config.module
      .rule('svg')
      .exclude.add(resolve('src/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    config
      .when(process.env.NODE_ENV !== 'development',
        config => {
          config
            .plugin('ScriptExtHtmlWebpackPlugin')
            .after('html')
            .use('script-ext-html-webpack-plugin', [{
            // `runtime` must same as runtimeChunk name. default is `runtime`
              inline: /runtime\..*\.js$/
            }])
            .end()
          config
            .optimization.splitChunks({
              chunks: 'all',
              cacheGroups: {
                libs: {
                  name: 'chunk-libs',
                  test: /[\\/]node_modules[\\/]/,
                  priority: 10,
                  chunks: 'initial' // only package third parties that are initially dependent
                },
                elementUI: {
                  name: 'chunk-elementUI', // split elementUI into a single package
                  priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                  test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
                },
                commons: {
                  name: 'chunk-commons',
                  test: resolve('src/components'), // can customize your rules
                  minChunks: 3, //  minimum common number
                  priority: 5,
                  reuseExistingChunk: true
                }
              }
            })
          // https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk
          config.optimization.runtimeChunk('single')
        }
      )
  },
  css: {
    loaderOptions: {
      less: {
        javascriptEnabled: true,
        modifyVars: {
          'primary-color': '#254184' // 全局主色
        }
      }
    }
  },
  pluginOptions: {
    'style-resources-loader': {
      preProcessor: 'less',
      // 需要通过less-loader自动引入资源，集合类型
      patterns: [path.resolve(__dirname, 'src/assets/style/_minxin.less')]
    }
  },
}
